package com.zsy.gateway.swagger;

import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.config.GatewayProperties;
import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**swagger资源提供者
 * @program: my-springcloud
 * @description:
 * @author: zhaoshouyun
 * @create: 2020-04-24 11:42
 **/
@Slf4j
//@Component
public class MySwaggerResourceProvider implements SwaggerResourcesProvider {

    /**
     * swagger2默认的url后缀
     */
    private static final String SWAGGER2URL = "v2/api-docs";

    /**
     * 网关路由
     */
    private final RouteLocator routeLocator;

    //此处可以不取网关，如果没有网关可以取服务发现的DiscoveryClientRouteDefinitionLocator 路由也是可以的
    private final GatewayProperties gatewayProperties;

    /**
     * 网关应用名称
     */
    @Value("${spring.application.name}")
    private String self;

    @Autowired
    public MySwaggerResourceProvider(RouteLocator routeLocator,GatewayProperties gatewayProperties) {
        this.routeLocator = routeLocator;
        this.gatewayProperties =gatewayProperties;
    }

    /**设置相关swagger资源
     * @Author zhaoshouyun
     * @Description
     * @Date 2020-04-24 02:55
     * @Param
     * @return java.util.List<springfox.documentation.swagger.web.SwaggerResource>
     **/
    @Override
    public List<SwaggerResource> get() {
        List<SwaggerResource> resources = new ArrayList<>();
        List<String> routes = new ArrayList<>();
        //取出gateway的route
        routeLocator.getRoutes().subscribe(route -> routes.add(route.getId()));

        //结合配置的route-路径(Path)，和route过滤，只获取有效的route节点
        gatewayProperties.getRoutes().stream().filter(routeDefinition -> routes.contains(routeDefinition.getId()))
                .forEach(routeDefinition -> routeDefinition.getPredicates().stream()
                        .filter(predicateDefinition -> ("Path").equalsIgnoreCase(predicateDefinition.getName()))
                        .forEach(predicateDefinition -> {
                            log.info(JSON.toJSONString(routeDefinition));

                            String urlPref="";
                            List<PredicateDefinition> predicates = routeDefinition.getPredicates();
                            //"predicates":[{"args":{"_genkey_0":"/api/login/**"}
                            for (PredicateDefinition predicate : predicates) {
                                //此处取的是Path 谓语下的，如果网关配置不一样，再此处修改就可以了
                                if ("Path".equals(predicate.getName())) {
                                    urlPref = predicate.getArgs().get("_genkey_0");
                                }
                            }
                            if (StringUtils.isNotBlank(urlPref)){
                                urlPref = urlPref.replace("**","");
                            }
                            resources.add(swaggerResource(routeDefinition.getId(),
                                    urlPref+SWAGGER2URL ));
                         }));

        return resources;
    }

    /**swaggerResource 资源配置
     * @Author zhaoshouyun
     * @Description
     * @Date 2020-04-24 02:53
     * @Param name
     * @Param location
     * @return springfox.documentation.swagger.web.SwaggerResource
     **/
    private SwaggerResource swaggerResource(String name, String location) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion("2.0");
        return swaggerResource;

    }
}
